package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"syscall"
)

var names = []string{
	"uts",
	"pid",
	//"mnt", // TODO: run in cgo
}

func doExec() {
	runtime.LockOSThread()

	var pid int
	var workDir string
	fs := flag.NewFlagSet("_exec", flag.ExitOnError)
	fs.IntVar(&pid, "pid", 0, "pid")
	fs.StringVar(&workDir, "w", "", "image dir")
	assert(fs.Parse(os.Args[2:]))

	for _, name := range names {
		fd, err := syscall.Open(fmt.Sprintf("/proc/%d/ns/%s", pid, name), syscall.O_RDONLY, 0644)
		assert(err)
		ret, _, msg := syscall.RawSyscall(308, uintptr(fd), 0, 0)
		if ret != 0 {
			fmt.Printf("%s failed, %d\n", name, msg)
		}
	}

	// TODO
	//assert(syscall.Chroot(workDir))

	args := fs.Args()
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	assert(cmd.Run())
}
